package com.qys.downservlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import com.qys.fileservice.fileService;
import com.qys.pojo.filedown;

@WebServlet("/down")
public class downservlet extends HttpServlet{
	private fileService service = new fileService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		LocalDate date = LocalDate.now();
		int month = date.getMonthValue();
		int today = date.getDayOfMonth();
		String path = "E:\\qiyuesuo\\"+month+"月"+today+"日";
		File file = new File(path);
		File[] files = file.listFiles();
		String filename = files[0].getName();
//		System.out.println(name);
//		String filename = name.substring(0, name.length()-4);
		double filesize = files[0].length();
		
		
		System.out.println("文件的名字："+filename);
		try {
			int num = service.proving(filename);
			if(num>=1){
				service.downFile(filename, filesize);
				resp.addHeader("content-disposition", "attachment;filename="+filename);//获取文件头信息
				FileUtils.copyFile(files[0], resp.getOutputStream());//将上面从下载源路径中获取的一个文件复制进响应地址。
				System.out.println("下载成功，文件名以及大小已经存入数据库");
			}
			else{
				System.out.println("该文件不是你上传，你无权下载");
				req.getRequestDispatcher("/WEB-INF/page/false.jsp").forward(req,resp);
			} 
							
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	  } 
	}

